package com.zhsj.OkeHomeConsumption.ui.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ClearEditText;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ElastticityScrollView;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ProgressDrawableAlertDialog;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.utils.CodeUtils;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;
import com.zhsj.OkeHomeConsumption.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;

import static com.zhsj.OkeHomeConsumption.ui.activity.wallet.BaseFragment.isFastDoubleClick;


/**
 * @author zhangpeisen
 * @ClassName: MineUserAuthFragment
 * @Description: TODO 实名认证
 * @date 2016年11月14日 下午3:01:55
 */
public class MineUserAuthFragment extends MyActivity implements OnClickListener {

    // 左标题
    private TextView topbar_textview_leftitle = null;
    // 主标题
    private TextView topbar_textview_title = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;
    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * @Fields neterror_relative : TODO
     */
    private RelativeLayout neterror_relative = null;
    /**
     * @Fields btn_loadingrefresh : TODO
     */
    private Button btn_loadingrefresh = null;
    // 真实姓名
    private ClearEditText edittext_realname;
    // 身份证号
    private ClearEditText edittext_idcardnum;
    // 银行卡号
    private ClearEditText edittext_bankcardnum = null;
    // 手机号
    private ClearEditText edittext_textView_moible = null;
    // 手机验证码
    private ClearEditText smscodenum_editext = null;
    /**
     * @Fields mSendsmsicon_tv : TODO 发送验证码按钮
     */
    private TextView mSendsmsicon_tv = null;
    // 提交认证信息
    private Button realauth_submit;

    private ElastticityScrollView elastticityScrollView = null;

    private int tag = -1;

    FormalUserInfo formalUserInfo;
    /**
     * @Fields mSendSmsCodeCount : TODO 发送短信验证码计时器
     */
    private SendSmsCodeCount mSendSmsCodeCount = null;

    private String serviceId = null;

    private View view_line2, view_line4, view_line5;
    // 身份证号模块
    private RelativeLayout relative_bankcardnum;
    // 预留手机号模块
    private RelativeLayout relative_moible;
    // 短信验证码
    private RelativeLayout smscodenum_rylayout;

    private String title;

//    public static MineUserAuthFragment newInstance(int tag, FormalUserInfo formalUserInfo, String title) {
//        Bundle args = new Bundle();
//        MineUserAuthFragment fragment = new MineUserAuthFragment();
//        args.putInt("tag", tag);
//        args.putString("title", title);
//        args.putSerializable("formalUserInfo", formalUserInfo);
//        fragment.setArguments(args);
//        return fragment;
//    }
//
//    @Override
//    public void onCreate(@Nullable Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        tag = getArguments().getInt("tag");
//        title = getArguments().getString("title");
//        formalUserInfo = (FormalUserInfo) getArguments().getSerializable("formalUserInfo");
//    }




    protected int getLayoutId() {
        // TODO Auto-generated method stub
        return R.layout.mine_realauth_fragment;
    }

    @Override
    protected int getTitleId() {
        return 0;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        formalUserInfo= (FormalUserInfo) bundle.getSerializable("formalUserInfo");
         // 初始化标题
        topbar_textview_leftitle = (TextView)  findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_title = (TextView)  findViewById(R.id.topbar_textview_title);
        topbar_textview_leftitle.setVisibility( View.VISIBLE);
        // 初始化Fragmemt 组件
        edittext_realname = (ClearEditText)  findViewById(R.id.edittext_realname);
        edittext_idcardnum = (ClearEditText)  findViewById(R.id.edittext_idcardnum);
        realauth_submit = (Button)  findViewById(R.id.realauth_submit);
        // 断网或者无网络状态下显示页面
        neterror_relative = (RelativeLayout)  findViewById(R.id.neterror_relative);
        btn_loadingrefresh = (Button)  findViewById(R.id.btn_loadingrefresh);
        elastticityScrollView = (ElastticityScrollView)  findViewById(R.id.srcollview);
        edittext_bankcardnum = (ClearEditText)  findViewById(R.id.edittext_bankcardnum);
        edittext_textView_moible = (ClearEditText)  findViewById(R.id.edittext_textView_moible);
        smscodenum_editext = (ClearEditText)  findViewById(R.id.smscodenum_editext);
        mSendsmsicon_tv = (TextView)  findViewById(R.id.sendsmsicon_tv);
        relative_bankcardnum = (RelativeLayout)  findViewById(R.id.relative_bankcardnum);
        relative_moible = (RelativeLayout)  findViewById(R.id.relative_moible);
        smscodenum_rylayout = (RelativeLayout)  findViewById(R.id.smscodenum_rylayout);
        view_line2 =  findViewById(R.id.view_line2);
        view_line4 =  findViewById(R.id.view_line4);
        view_line5 =  findViewById(R.id.view_line5);
//        if (TextUtils.isEmpty(title)) {
//            return;
//        }
//        if (title.equals("0")) {
//            topbar_textview_title.setText("绑定银行卡");
//            realauth_submit.setText("确认绑定");
//        } else {
            topbar_textview_title.setText("实名认证");
            realauth_submit.setText("提交认证信息");
//        }
        addLinstener();
    }



    /**
     * @Title: initData @Description: TODO 初始化数据 @param @return void
     * 返回类型 @throws
     */
    @SuppressLint({"SetJavaScriptEnabled", "InlinedApi", "NewApi"})
    protected void initData() {
        // TODO Auto-generated method stub
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(getActivity());
//        mSendSmsCodeCount = new SendSmsCodeCount(60 * 1000, 100);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (!Utils.isNetWorkConnected(getActivity())) {
            // 无网络的状态下
            neterror_relative.setVisibility(View.VISIBLE);
            elastticityScrollView.setVisibility(View.GONE);
        } else {
            // 有网络的状态下
            neterror_relative.setVisibility(View.GONE);
            elastticityScrollView.setVisibility(View.VISIBLE);
            if (formalUserInfo == null) {
                realauth_submit.setVisibility(View.VISIBLE);
//                view_line2.setVisibility(View.VISIBLE);
//                view_line4.setVisibility(View.VISIBLE);
//                view_line5.setVisibility(View.VISIBLE);
                return;
            }
            if (formalUserInfo.getUserAuthentic() == null) {
                realauth_submit.setVisibility(View.VISIBLE);
//                view_line2.setVisibility(View.VISIBLE);
//                view_line4.setVisibility(View.VISIBLE);
//                view_line5.setVisibility(View.VISIBLE);
            } else {
                if (formalUserInfo.getUserAuthentic().isAuthenticated()) {
                    // 认证成功
                    realauth_submit.setVisibility(View.GONE);
                    relative_bankcardnum.setVisibility(View.GONE);
                    relative_moible.setVisibility(View.GONE);
                    smscodenum_rylayout.setVisibility(View.GONE);
                    view_line2.setVisibility(View.GONE);
                    view_line4.setVisibility(View.GONE);
                    view_line5.setVisibility(View.GONE);
                    edittext_realname.setText(formalUserInfo.getUserAuthentic().getName());
                    edittext_realname.setEnabled(false);
                    edittext_realname.setFocusable(false);
                    edittext_realname.setFocusableInTouchMode(false);
                    edittext_idcardnum.setText(formalUserInfo.getUserAuthentic().getIdCard());
                    edittext_idcardnum.setEnabled(false);
                    edittext_idcardnum.setFocusable(false);
                    edittext_idcardnum.setFocusableInTouchMode(false);
                } else {
                    //认证失败
                    realauth_submit.setVisibility(View.VISIBLE);
                    relative_bankcardnum.setVisibility(View.VISIBLE);
//                    view_line2.setVisibility(View.VISIBLE);
//                    view_line4.setVisibility(View.VISIBLE);
//                    view_line5.setVisibility(View.VISIBLE);
                }
            }

        }
    }

    /**
     * @Title: addLinstener @Description: TODO 添加视图监听器 @param @return void
     * 返回类型 @throws
     */
    protected void addLinstener() {
        // TODO Auto-generated method stub
        topbar_textview_leftitle.setOnClickListener(this);
        btn_loadingrefresh.setOnClickListener(this);
        realauth_submit.setOnClickListener(this);
        mSendsmsicon_tv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.topbar_textview_leftitle:
              finish();
                break;
            case R.id.btn_loadingrefresh:
                if (isFastDoubleClick()) {
                    return;
                }
                if (!Utils.isNetWorkConnected(getActivity())) {
                    // 无网络的状态下
                    neterror_relative.setVisibility(View.VISIBLE);
                    elastticityScrollView.setVisibility(View.GONE);
                 finish();
                    toast("网络状态弱，请重试");
                } else {
                    // 有网络的状态下
                    neterror_relative.setVisibility(View.GONE);
                    elastticityScrollView.setVisibility(View.VISIBLE);

                }
                break;
//            case R.id.sendsmsicon_tv:
//                // 发送验证码
//                String strRealname = edittext_realname.getText().toString().trim();
//                String strIdcardnum = edittext_idcardnum.getText().toString().trim();
//                String strBankcardnum = edittext_bankcardnum.getText().toString().trim();
//                String strMoible = edittext_textView_moible.getText().toString().trim();
//                if (TextUtils.isEmpty(strMoible)) {
//                    showShortToast("请填写手机号");
//                    return;
//                }
//                if (!DataVerifyUtils.verifyTelNum(strMoible)) {
//                    showShortToast("请输入正确的手机号码");
//                    return;
//                }
//                if (DataVerifyUtils.isIDCard(strIdcardnum) == false) {
//                    showShortToast("请填写正确的身份证号");
//                    return;
//                }
//                if (TextUtils.isEmpty(strBankcardnum)) {
//                    showShortToast("请填写银行卡号");
//                    return;
//                }
//                if (TextUtils.isEmpty(strRealname)) {
//                    showShortToast("请填写姓名");
//                    return;
//                }
//                // 实名验证码
//                UserAutenticPost(strIdcardnum, strRealname, strBankcardnum, strMoible);
//                break;
            case R.id.realauth_submit:
                // 提交认证信息
                if (isFastDoubleClick()) {
                    return;
                }
                String str_realname = edittext_realname.getText().toString().trim();
                String str_idcardnum = edittext_idcardnum.getText().toString().trim();
//                String edittext_bankcardnum_str = edittext_bankcardnum.getText().toString().trim();
//                String edittext_textView_moible_str = edittext_textView_moible.getText().toString().trim();
//                String smscodenum_editext_str = smscodenum_editext.getText().toString().trim();
                if (TextUtils.isEmpty(str_realname)) {
                    toast("请填写真实姓名");
                    return;
                }
                if (TextUtils.isEmpty(str_idcardnum)) {
                    toast("请填写身份证号");
                    return;
                }
//                if (TextUtils.isEmpty(edittext_bankcardnum_str)) {
//                    showShortToast("请填写银行卡号");
//                    return;
//                }
//                if (TextUtils.isEmpty(edittext_textView_moible_str)) {
//                    showShortToast("请填写手机号");
//                    return;
//                }
//                if (TextUtils.isEmpty(smscodenum_editext_str)) {
//                    showShortToast("请输入验证码");
//                    return;
//                }

                if(!personIdValidation(str_idcardnum)){
                    toast("请输入正确的身份证号码");
                    return;
                }
                // 实名认证异步处理方法
                UserVerificationPost(str_idcardnum, str_realname
                        );
                break;
            default:
                break;
        }
    }
    /**
     * 验证身份证号是否符合规则
     * @param text 身份证号
     * @return
     */
    public boolean personIdValidation(String text) {
        String regx = "[0-9]{17}x";
        String reg1 = "[0-9]{15}";
        String regex = "[0-9]{18}";
        return text.matches(regx) || text.matches(reg1) || text.matches(regex);
    }
    /**
     * 实名认证异步处理方法
     *
     * @param
     * @return 创建时间：2017/1/19 15:08
     */
    public void UserVerificationPost(String idCard, String name) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mVerificationHashMap = new HashMap<String, String>();
        mVerificationHashMap.put("v", Constants.APPVERSION);
        mVerificationHashMap.put("t", Constants.TIME);
        mVerificationHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mVerificationHashMap.put("platform", Constants.PLAFORM);
        mVerificationHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mVerificationHashMap.put("client", Constants.CLIENT);
        String idcard1 = idCard.substring(0,11);
        String idcard2 = idCard.substring(11);
        String phoneString  = CodeUtils.encryptAES(idcard1, CodeUtils.password);
        String phoneString2  = CodeUtils.encryptAES(idcard2, CodeUtils.password);
        mVerificationHashMap.put("idCard1", phoneString);
        mVerificationHashMap.put("idCard2", phoneString2);
        mVerificationHashMap.put("name", name);
        paramMaps.put("idCard1", phoneString);
        paramMaps.put("idCard2", phoneString2);

        paramMaps.put("name", name);
        if (!TextUtils.isEmpty(serviceId)) {
            mVerificationHashMap.put("serviceId", serviceId);
            paramMaps.put("serviceId", serviceId);
        }
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mVerificationHashMap);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_ERYAOSU, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        Bundle bundle = new Bundle();
                        toast("恭喜，验证成功");
                        bundle.putString("auth", "已认证");
//                       / setFragmentResult(RESULT_OK, bundle);
                      finish();
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    LogUtils.e("UserVerificationPost", "sendcode异常 ");
                }

            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });

    }


    /**
     * @author zhangpeisen
     * @ClassName: SendSmsCodeCount
     * @Description: TODO 发送短信验证码的线程
     * @date 2016年9月13日 下午4:41:30
     */
    class SendSmsCodeCount extends CountDownTimer {

        public SendSmsCodeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mSendsmsicon_tv.setEnabled(true);
            mSendsmsicon_tv.setTextColor(Color.parseColor("#79AB1C"));
            mSendsmsicon_tv.setGravity(Gravity.CENTER);
            mSendsmsicon_tv.setTextSize(14);
            mSendsmsicon_tv.setText("发送");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mSendsmsicon_tv.setEnabled(false);
            if (millisUntilFinished / 1000 == 0) {
                onFinish();
            } else {
                mSendsmsicon_tv.setText(millisUntilFinished / 1000 + "");
                mSendsmsicon_tv.setTextColor(Color.parseColor("#B2B2B2"));
                mSendsmsicon_tv.setGravity(Gravity.CENTER);
                mSendsmsicon_tv.setTextSize(14);
            }
        }
    }


    /**
     * 实名验证码异步处理方法
     *
     * @param
     * @return 创建时间：2017/1/19 15:08
     */
    public void UserAutenticPost(String idCard, String name, String cardno, String mobile) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        LogUtils.e("UserAutenticPost time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        mLogOnHashMap.put("idCard", idCard);
        mLogOnHashMap.put("name", name);
        mLogOnHashMap.put("cardno", cardno);
        mLogOnHashMap.put("mobile", mobile);
        //
        paramMaps.put("idCard", idCard);
        paramMaps.put("name", name);
        paramMaps.put("cardno", cardno);
        paramMaps.put("mobile", mobile);
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_USERAUTENTIC, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        mSendSmsCodeCount.start();
                        toast("验证码已发送");
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        serviceId = jsonObject.optString("serviceId");
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    LogUtils.e("UserAutenticPost", "sendcode异常 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });

    }


}
